/**
 * Copyright © 2008, EMC Corporation.
 * Redistribution and use in source and binary forms, with or without modification, 
 * are permitted provided that the following conditions are met:
 *
 *     + Redistributions of source code must retain the above copyright notice, 
 *       this list of conditions and the following disclaimer.
 *     + Redistributions in binary form must reproduce the above copyright 
 *       notice, this list of conditions and the following disclaimer in the 
 *       documentation and/or other materials provided with the distribution.
 *     + The name of EMC Corporation may not be used to endorse or promote 
 *       products derived from this software without specific prior written 
 *       permission.
 *
 *      THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 *      "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 
 *      TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 
 *      PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS 
 *      BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 
 *      CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 
 *      SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 
 *      INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 *      CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 
 *      ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 *      POSSIBILITY OF SUCH DAMAGE.
 */
package com.emc.esu.helpers {
	import com.emc.esu.api.Acl;
	import com.emc.esu.api.Checksum;
	import com.emc.esu.api.EsuApi;
	import com.emc.esu.api.EsuCallbackState;
	import com.emc.esu.api.EsuError;
	import com.emc.esu.api.Extent;
	import com.emc.esu.api.Identifier;
	import com.emc.esu.api.MetadataList;
	import com.emc.esu.api.ObjectId;
	import com.emc.esu.api.ObjectPath;
	
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.utils.ByteArray;
	import flash.utils.IDataInput;
	import flash.utils.Timer;
	
	import mx.logging.ILogger;
	import mx.logging.Log;
	/**
	 * Dispatched when the download helper has completed
	 * @eventType flash.events.Event.COMPLETE
	 */
	[Event(name="complete", type="flash.events.Event")]
	/**
	 * Dispatched when the download helper encounters an error
	 * @eventType flash.events.ErrorEvent.ERROR
	 */
	[Event(name="error", type="flash.events.ErrorEvent")]
	/**
	 * Dispatched as data chunks are read from the server
	 * @eventType flash.events.ProgressEvent.PROGRESS
	 */
	[Event(name="progress", type="flash.events.ProgressEvent")]
	/**
	 * Helper class to create and update objects.  For large transfers, the content
	 * generally needs to be transferred to the server in smaller chunks.  This
	 * class reads data from a stream and incrementally uploads it
	 * to the server.
	 */
	public class UploadHelper extends EventDispatcher {
		private const DEFAULT_BUFFSIZE:int = 4096 * 1024; // 4MB

	    private var _buffer:ByteArray;
	    private var _requestSize:int;
	    private var _esu:EsuApi;
	    private var _stream:IDataInput;
	    private var _bytesLoaded:Number;
	    private var _bytesTotal:Number;
	    private var _complete:Boolean;
	    private var _failed:Boolean;
	    private var _error:Error;
	    private var _objectId:Identifier;
	    private var _readTimer:Timer;
	    private var _running:Boolean;
	    private var _checksumming:Boolean;
	    private var _checksum:Checksum;
	    private var _mimeType:String;
	    
	    private var logger:ILogger;
	    
	    [Bindable]
	    /**
	     * The number of bytes uploaded.
	     */
	    public function get bytesLoaded():Number {
	    	return _bytesLoaded;
	    }
	    public function set bytesLoaded( val:Number ):void {
	    	this._bytesLoaded = val;
	    }
	    
	    [Bindable]
	    /**
	     * The total number of bytes to upload.
	     */
	    public function get bytesTotal():Number {
	    	return this._bytesTotal;
	    }
	   	public function set bytesTotal( val:Number ):void {
	   		this._bytesTotal = val;
	   	}
	   	
	   	[Bindable]
	   	/**
	   	 * Set to true when the upload has completed.
	   	 */
	   	public function get complete():Boolean {
	   		return this._complete;
	   	}
	   	public function set complete( val:Boolean ):void {
	   		this._complete = val;
	   	}
	   	
	   	[Bindable]
	   	/**
	   	 * Set to true if the upload has failed.
	   	 */
	   	public function get failed():Boolean {
	   		return this._failed;
	   	}
	   	public function set failed( val:Boolean ):void {
	   		this._failed = val;
	   	}
	   	
	   	[Bindable]
	   	/**
	   	 * If the upload has failed, this contains the error.
	   	 */
	   	public function get error():Error {
	   		return this._error;
	   	}
	   	public function set error( val:Error ):void {
	   		this._error = val;
	   	}

		[Bindable]
		/**
		 * Contains the object ID that is being uploaded.
		 */
		public function get objectId():Identifier {
			return this._objectId;
		}
		public function set objectId( val:Identifier ):void {
			this._objectId = val;
		}
		
		[Bindable]
		public function get checksumming():Boolean {
			return this._checksumming;
		}
		public function set checksumming( val:Boolean ):void {
			this._checksumming = checksumming;
		}
		
		[Bindable]
		public function get mimeType():String {
			return this._mimeType;
		}
		public function set mimeType( val:String ):void {
			this._mimeType = val;
		}
	
		/**
		 * Creates a new upload helper.
		 * @param esu the EsuApi object to use for the uploads.
		 * @param buffsize the number of bytes to upload in each chunk.  By default,
		 * this is 4MB.
		 */
		public function UploadHelper( esu:EsuApi, buffsize:int = DEFAULT_BUFFSIZE ):void {
			this.logger = Log.getLogger("EsuApi");
			this._esu = esu;
			this._buffer = new ByteArray();
			this._requestSize = buffsize;
			this._readTimer = new Timer( 100, 1 );
			this._readTimer.addEventListener( TimerEvent.TIMER, onReadTimer );
		}

		/**
		 * Creates a new object on the server.  When the complete event is fired, you
		 * can get the new object's ID from the objectId property.
		 * @param stream the data to upload
		 * @param streamLength the number of bytes to upload from the stream
		 * @param acl the ACL for the new object.  May be null.
		 * @param metadata metadata to assign to the new object.  May be null.
		 */
	    public function createObject( stream:IDataInput, streamLength:Number, acl:Acl,
        	metadata:MetadataList ):void {
        		
        	this.bytesLoaded = 0;
        	this.bytesTotal = streamLength;
	        this.complete = false;
	        this.failed = false;
	        this.error = null;
	        this._stream = stream;
	        this._running = true;
	        
	        try {
	        	// Use create on first call to create the object.
	        	var eof:Boolean = readChunk();
	        	if( _checksumming ) {
	        		_checksum = new Checksum( Checksum.ALGORITHM_SHA0 );
	        	}
	        	this._esu.createObject( null, metadata, this._buffer, _mimeType, handleCreateObjectResponse, eof, _checksum );
	        } catch( e:Error ) {
	        	fail( e );
	        }

        }
        
		/**
		 * Creates a new object on the server.  When the complete event is fired, you
		 * can get the new object's ID from the objectId property.
		 * @param stream the data to upload
		 * @param streamLength the number of bytes to upload from the stream
		 * @param acl the ACL for the new object.  May be null.
		 * @param metadata metadata to assign to the new object.  May be null.
		 */
	    public function createObjectOnPath( path:ObjectPath, stream:IDataInput, streamLength:Number, acl:Acl,
        	metadata:MetadataList ):void {
        		
        	this.bytesLoaded = 0;
        	this.bytesTotal = streamLength;
	        this.complete = false;
	        this.failed = false;
	        this.error = null;
	        this._stream = stream;
	        this._running = true;
	        
	        try {
	        	// Use create on first call to create the object.
	        	var eof:Boolean = readChunk();
	        	if( _checksumming ) {
	        		_checksum = new Checksum( Checksum.ALGORITHM_SHA0 );
	        	}
	        	this._esu.createObjectOnPath(path, null, metadata, this._buffer, _mimeType, handleCreateObjectResponse, eof, _checksum );
	        } catch( e:Error ) {
	        	fail( e );
	        }

        }
        
        /**
         * Updates an existing object on the server.
         * @param id the object to update
         * @param stream the new data for the object.
         * @param streamLength the number of bytes to upload from the stream
         * @param acl the new ACL for the object.  May be null.
         * @param metadata new metadata for the object.  May be null.
         */
	    public function updateObject( id:Identifier, stream:IDataInput, streamLength:Number, acl:Acl,
        	metadata:MetadataList ):void {
        		
        	this._objectId = id;
        	this.bytesLoaded = 0;
        	this.bytesTotal = streamLength;
	        this.complete = false;
	        this.failed = false;
	        this.error = null;
	        this._stream = stream;
	        this._running = true;
	        
	        try {
	        	// First call uses a null extent to truncate the file.
	        	var eof:Boolean = readChunk();
	        	if( _checksumming ) {
	        		_checksum = new Checksum( Checksum.ALGORITHM_SHA0 );
	        	}

	        	this._esu.updateObject( this._objectId, null, metadata, null, this._buffer, _mimeType, handleUpdateObjectResponse, eof, _checksum );
	        } catch( e:Error ) {
	        	fail( e );
	        }
        	
        }
        
        /**
         * Cancels the upload
         */
   		public function cancel():void {
			logger.debug( "Transfer canceled" );
			this._running = false;
		}

        /**
         * Handles the create object response.  Extracts the object ID and continues
         * the upload if needed.
         * @param state the callback state from the createObject request.
         */
        private function handleCreateObjectResponse( state:EsuCallbackState ):void {
        	if( !state.wasSuccessful() ) {
        		fail( state.getError() );
        		return;
        	}
        	
        	this._objectId = ObjectId( state.getResult() );
        	progress( this._buffer.length );
        	var eof:Boolean = Boolean( state.getStateObject() );
        	if( eof ) {
        		// No data was sent with the first request, so we're done
        		done();
        		return;
        	}     	
        	
        	appendChunks();
        }
        
        /**
         * Handles the response from the first updateObject request.  Continues
         * uploading if requred.
         * @param state the callback state from the updateObject request.
         */
        private function handleUpdateObjectResponse( state:EsuCallbackState ):void {
        	if( !state.wasSuccessful() ) {
        		fail( state.getError() );
        		return;
        	}
        	progress( this._buffer.length );
        	var eof:Boolean = Boolean( state.getStateObject() );
        	if( eof ) {
        		// No data was sent with the first request, so we're done
        		done();
        		return;
        	}
        		
        	appendChunks();
        }
        
        /**
         * Continues appending chunks to the object
         */
        private function appendChunks():void {
            if( !this._running ) {
            	// Transfer canceled
            	fail( new EsuError( "Transfer canceled" ) );
            	return;
            }
            
        	var eof:Boolean = readChunk();
            if (eof) {
                // done
                done();
                return;
            }
            
            if( this._buffer.length == 0 ){
            	// No bytes ready to be read.  Schedule another try for 100ms
            	// in the future.
            	logger.debug( "Zero bytes available.  Sleeping" );
            	this._readTimer.start();
            	return;
            }

            var extent:Extent = new Extent( this._bytesLoaded, this._buffer.length );
            this._esu.updateObject( _objectId, null, null, extent, this._buffer, null, handleAppendChunkResponse, null, _checksum );
        }
        /**
         * Handles responses from appending chunks.  Updates progress and moves on to the 
         * next chunk.
         */
        private function handleAppendChunkResponse( state:EsuCallbackState ):void {
        	if( !state.wasSuccessful() ) {
        		fail( state.getError() );
        		return;
        	}
        	
        	progress( this._buffer.length );
        	appendChunks();
        }
        
        /**
         * Updates the upload progress and fires progress events.
         */
        private function progress( bytes:int ):void {
        	this.bytesLoaded += bytes;
        	var event:ProgressEvent = new ProgressEvent( ProgressEvent.PROGRESS );
        	event.bytesLoaded = this._bytesLoaded;
        	event.bytesTotal = this._bytesTotal;

        	this.dispatchEvent( event );
        }
        
        /**
         * Fails the upload request and fires error events.
         */
        private function fail( e:Error ):void {
        	this.failed = true;
        	this.error = e;
        	
        	var event:ErrorEvent = new ErrorEvent( ErrorEvent.ERROR, false, false, e.message );
        	this.dispatchEvent( event );
        }

		/**
		 * Completes the upload request and fires complete events.
		 */
		private function done():void {
			this.complete = true;
			
			var event:Event = new Event( Event.COMPLETE );
			this.dispatchEvent( event );
		}
		
		/**
		 * Reads a chunk from the input stream.
		 * @return true if an EOF was encountered reading the stream.
		 */
		private function readChunk():Boolean {
			if( this._bytesLoaded >= this._bytesTotal ) {
				return true;
			}
			
			var readSize:int = this._stream.bytesAvailable;
			if( readSize > this._requestSize ) {
				readSize = this._requestSize;
			}
			
			// See if any data is ready
			if( this._stream.bytesAvailable > 0 ) {
				this._buffer.length = readSize;
				this._stream.readBytes( this._buffer, 0, readSize );
				this._buffer.position = 0;
			} else {
				this._buffer.length = 0;
			}
			
			return false;
		}
		
		/**
		 * Called when the read timer wakes up.  The read timer is used if the
		 * input stream has no bytes available to upload.
		 */
		private function onReadTimer( event:TimerEvent ):void {
			logger.debug( "Read timer wakeup" );
			appendChunks();
		}
		
	}
}